package com.apes.fn.scm.crossCompany.transfer.model;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.LogicalUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.stock.model.Location;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.scm.crossCompany.transfer.model
 * @ClassName: CrossCompanyTransfer
 * @Author: pyb
 * @CreateTime: 2020-06-19 16:20
 * @Description: 跨公司调拨
 * @Version: 1.0
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = CrossCompanyTransfer.CONST_TABLE_NAME)
public class CrossCompanyTransfer extends Model {
    public static final String CONST_TABLE_NAME = "cross_company_transfer";
    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "跨公司调拨单", prefix = "DB%(company)%(yy)%(month)", padding = 5, useDateRange=true)
    private String id;

    @Column(name = "source", length = 30)
    @Comment("上游单据")
    private String source;

    @Column(name = "source_business_type", length = 32)
    @Comment("上游单据类型")
    private String sourceBusinessType;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司")
    private PartyRole company;


    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ship_location_id", referencedColumnName = "id")
    @Comment("发货仓库")
    private Location shipLocation;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "receipt_location_id", referencedColumnName = "id")
    @Comment("收货仓库")
    private Location receiptLocation;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "move_type", referencedColumnName = "id")
    @Comment("原因")
    private Enumeration returnReason;


    @Column(name = "state", length = 10, nullable = false)
    @States(name = "订单状态", values = {
            @State(id = "sent", name = "新建"),
            @State(id = "apply", name = "申请"),
            @State(id = "approve", name = "审核"),
            @State(id = "reject", name = "驳回"),
            @State(id = "done", name = "已完成"),
            @State(id = "receipt", name = "已收货"),
            @State(id = "delivered", name = "待发货"),
            @State(id = "ship", name = "已发货")})
    private String state;

    @Column(name = "cross_system", length = 36)
    @States(name = "跨系统", values = {
            @State(id = "erp", name = "老系统"),
            @State(id = "unidentified", name = "未鉴定"),
            @State(id = "esb", name = "新系统")})
    private String crossSystem;

    /**
     * 功能: 判断当前单据是否需要发货
     */
    @Transient
    @States(name = "需要收货", values = {
            @State(id = "yes", name = "需发货"),
            @State(id = "no", name = "无需发货")})
    private String needShip;

    public String getNeedShip() {
        Set<CrossCompanyTransferItem> items = this.crossCompanyTransferItems.stream()
                .filter(orderItem -> LogicalUtil.notIn(orderItem.getProduct().getType(), "aut"))
                .collect(Collectors.toSet());
        return items.isEmpty() ? "no" : "yes";
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "transfer_type", referencedColumnName = "id")
    @Comment("调拨类型")
    private Enumeration transferType;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid;

    @Column(name = "date_approve")
    @Comment("审批日期")
    private Date dateApprove;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "apply_uid", referencedColumnName = "id")
    @Comment("申请人")
    private PartyRole applyUid;

    @Column(name = "date_apply")
    @Comment("申请日期")
    private Date dateApply;


    @Column(name = "note")
    @Comment("备注")
    private String note;

    @Column(name = "amt_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double amtTax = 0;

    @Column(name = "amt_untaxed", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("不含税金额")
    private double amtUntaxed = 0;

    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double amtTotal = 0;


    @Column(name = "qty_received", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("已收货数量")
    private double qtyReceived = 0;



    @Column(name = "qty_total", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("收货总数量")
    private double qtyTotal= 0;

    @Column(name = "print_number", columnDefinition = "number(4,0) default 0")
    @Comment("打印次数")
    private double printNumber;



    @OneToMany(mappedBy = "crossCompanyTransfer", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<CrossCompanyTransferItem> crossCompanyTransferItems = new HashSet<>();

    public Set<CrossCompanyTransferItem> getCrossCompanyTransferItems() {
        for (CrossCompanyTransferItem item : crossCompanyTransferItems) {
            item.setCrossCompanyTransfer(this);
            item.setCompany(company);
        }
        return crossCompanyTransferItems;
    }

    public void computeAmt() {
        amtUntaxed = 0; amtTax = 0;
        for (CrossCompanyTransferItem item : crossCompanyTransferItems) {
            item.computeAmt();
            amtUntaxed += item.getPriceSubtotal();
            amtTax += item.getPriceTax();
        }
        amtTotal = amtUntaxed + amtTax;
    }

    /**
     * 更新发货数量
     */
    public void delivery(double qtyDone) {
        this.qtyReceived += qtyDone;
        if (qtyReceived > qtyTotal) {
            throw new RuntimeException("接收数量不允许大于订单数量！");
        }
    }
}
